package cn.khson.vrd.controller;

import cn.khson.vrd.entity.Banner;
import cn.khson.vrd.mapper.BannerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class BannerController {
    @Autowired(required = false)
    private BannerMapper mapper;
    @RequestMapping("/banner/list")
    public List<Banner> bannerList(){
        return mapper.bannerList();
    }

    @RequestMapping("/banner/delete")
    public void delete(int id){
        mapper.deleteById(id);
    }

    @RequestMapping("/banner/add")
    public void add(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        String dirPath = "D:/IdeaProjects/upload";
//        String dirPath = "./src/main/resources/static/images";//tomcat报错(找不到路径)
        File dirFile = new File(dirPath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+"/"+fileName;
        file.transferTo(new File(filePath));
        Banner banner = new Banner();
        banner.setUrl(fileName);
        mapper.insert(banner);
    }

}
